//
//  XMGMeViewController.m
//  BuDeJie
//
//  Created by xiaomage on 16/3/11.
//  Copyright © 2016年 小码哥. All rights reserved.
//

#import "XMGMeViewController.h"
#import "XMGSettingViewController.h"
#import <AFNetworking/AFNetworking.h>
#import "XMGSquareItem.h"
#import <MJExtension/MJExtension.h>

#import "XMGWebViewController.h"

#import "XMGSquareCell.h"
/*
    搭建基本结构 -> 设置底部条 -> 设置顶部条 -> 设置顶部条标题字体 -> 处理导航控制器业务逻辑(跳转)
 
 */
static NSString * const ID = @"cell";
static NSInteger const cols = 4;
static CGFloat const margin = 1;
#define itemWH (XMGScreenW - 3 * margin) / cols

@interface XMGMeViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic, strong) AFHTTPSessionManager *mgr;
@property (nonatomic, strong) NSMutableArray *SquareItems;

@property (nonatomic, weak) UICollectionView *collectionView;

@end


@implementation XMGMeViewController

-(AFHTTPSessionManager *)mgr
{
    if (_mgr == nil) {
        _mgr = [AFHTTPSessionManager manager];
    }
    return _mgr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置导航条
    [self setupNavBar];
 
    [self setfootView];

    [self loadData];
    
    self.tableView.sectionFooterHeight = 10;
    self.tableView.sectionHeaderHeight = 0;
    
    self.tableView.contentInset = UIEdgeInsetsMake(-25, 0, 0, 0);
}

-(void)loadData
{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"] = @"square";
    parameters[@"c"] = @"topic";
    
    [self.mgr GET:XMGCommonURL parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary  *responseObject) {
//        [responseObject writeToFile:@"/Users/chenhengjun/Desktop/me.plist" atomically:YES];
        NSArray *dataArray =  responseObject[@"square_list"];
        _SquareItems = [XMGSquareItem mj_objectArrayWithKeyValuesArray:dataArray];
        
        [self resloveData];
        
        NSInteger count = self.SquareItems.count;
        NSInteger row = (count -1) / cols + 1;
        
        self.collectionView.xmg_height = row * itemWH;
        
        self.tableView.tableFooterView = self.collectionView;
        
        [self.collectionView reloadData];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
    
    
}

-(void)resloveData
{
    NSInteger count = self.SquareItems.count;
    NSInteger exter = count % cols;
    if (exter) {
        exter = cols - exter;
        for (int i = 0; i < exter; ++i) {
            XMGSquareItem *item = [[XMGSquareItem alloc] init];
            [self.SquareItems addObject:item];;
        }
    }
}

-(void)setfootView
{
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    

    flowLayout.itemSize = CGSizeMake(itemWH, itemWH);
    flowLayout.minimumLineSpacing = 1;
    flowLayout.minimumInteritemSpacing = 1;
    
    
    UICollectionView *collectionV = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 300) collectionViewLayout:flowLayout];
    
    collectionV.dataSource = self;
    collectionV.delegate =self;
    collectionV.scrollEnabled = NO;
    collectionV.backgroundColor = self.tableView.backgroundColor;
    
    
    
    self.tableView.tableFooterView = collectionV;
    
    self.collectionView = collectionV;
    
//    [collectionV registerClass:[XMGSquareCell class] forCellWithReuseIdentifier:ID];
    [collectionV registerNib:[UINib nibWithNibName:NSStringFromClass([XMGSquareCell class]) bundle:nil] forCellWithReuseIdentifier:ID];
}

- (void)setupNavBar
{
    // 左边按钮
    // 把UIButton包装成UIBarButtonItem.就导致按钮点击区域扩大
    
    // 设置
    UIBarButtonItem *settingItem =  [UIBarButtonItem itemWithimage:[UIImage imageNamed:@"mine-setting-icon"] highImage:[UIImage imageNamed:@"mine-setting-icon-click"] target:self action:@selector(setting)];

    // 夜间模型
    UIBarButtonItem *nightItem =  [UIBarButtonItem itemWithimage:[UIImage imageNamed:@"mine-moon-icon"] selImage:[UIImage imageNamed:@"mine-moon-icon-click"] target:self action:@selector(night:)];

    self.navigationItem.rightBarButtonItems = @[settingItem,nightItem];
    
    // titleView
    self.navigationItem.title = @"我的";
    
}

- (void)night:(UIButton *)button
{
    button.selected = !button.selected;
    
}

#pragma mark - 设置就会调用
- (void)setting
{
    // 跳转到设置界面
    XMGSettingViewController *settingVc = [[XMGSettingViewController alloc] init];
    // 必须要在跳转之前设置
    settingVc.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:settingVc animated:YES];
    

    
}

#pragma mark - UICollectionViewDelegate

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    XMGSquareItem *item = self.SquareItems[indexPath.row
                                           ];
    if (![item.url containsString:@"http"]) return;
    
    
//    SFSafariViewController *safariVC = [[SFSafariViewController alloc ] initWithURL:[NSURL URLWithString:item.url]];
    
    
    XMGWebViewController *webVC = [[XMGWebViewController alloc] init];
    webVC.url = [NSURL URLWithString:item.url];
    [self.navigationController pushViewController:webVC animated:YES];
    
    

}
#pragma mark - UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.SquareItems.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    XMGSquareCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    
//    cell.backgroundColor = [UIColor purpleColor];
    cell.item = self.SquareItems[indexPath.item];
    return cell;
    
}

#pragma mark - Table view data source

//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Incomplete implementation, return the number of sections
//    return 0;
//}
//
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//#warning Incomplete implementation, return the number of rows
//    return 0;
//}



@end
